import { ElMessage } from "element-plus";
import router from "./router"
import { useUserStore } from "./stores/user";
import { getProfileAPI } from "./apis/user";
import { it } from "element-plus/es/locales.mjs";
import type { RouteRecordRaw } from "vue-router";
import { asyncRoutes } from "./router/asyncRoutes";
import { useMenuStore } from "./stores/menu";

const WHITE_LIST = ['/login','/404']

//处理一级路由数据
const getFirstRoutePerms = (permsArr:string[])=>{
  const tempArr = permsArr.map(item=>item.split(':')[0])
  return Array.from(new Set(tempArr))
}
//处理二级路由数据
const getSecondRoutePerms = (permsArr:string[])=>{
  const newArr = permsArr.map(item=>{
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(newArr))
}

router.beforeEach(async(to,from,next)=>{
  console.log(to);
  const store = useUserStore()
  if(store.token){
    next()
    if(!store.profile.id){
      const res = await getProfileAPI()
      console.log('获取用户信息',res);
      store.setProfile(res.data)
      console.log('用户信息',res.data.permissions);
      const menus = getFirstRoutePerms(res.data.permissions)
      const smenus = getSecondRoutePerms(res.data.permissions)
      const perRoutes = getRoutes(menus,smenus,asyncRoutes)
      // 4. 把动态路由表加入到路由系统中（当浏览器中访问路由的路径 显示渲染出来对应的组件）
      perRoutes.forEach(route=>{
        router.addRoute(route as RouteRecordRaw)
      })
      // 3. 保存侧栏菜单路由
      const menuStore = useMenuStore()
      menuStore.setMenuList(perRoutes as RouteRecordRaw[])
      next({...to})
    }else{
      next()
    }
  }else{
    if(WHITE_LIST.includes(to.path)){
      next()
    } else{
      next('/login')
      ElMessage.warning('请先登录！！！！')
    }
  }
})

// 根据权限筛选出匹配的路由
const getRoutes = (firstRoutePerms:string[],secondRoutePerms:string[],asyncRoutes:RouteRecordRaw[])=>{
  console.log(firstRoutePerms, secondRoutePerms, asyncRoutes);
  if(firstRoutePerms.includes('*')){
    return [...asyncRoutes]
  }
  // 过滤出一级路由
  const firstRoutes = asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.meta!.permission!)
  })
  // 基于筛选的一级路由，继续筛选二级路由
  const lastRoutes = firstRoutes.map(route => {
    return {
      ...route,
      // 筛选二级路由
      children: route.children?.filter(v=> secondRoutePerms.includes(v.meta!.permission!))
    }
  })
  return lastRoutes
}

